import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox
import json
from pathlib import Path
from typing import List, Tuple, Set, Union, Dict, Any

# Add project root to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

# Import system modules
from User.Student import Student
from User.Teacher import Teacher
from User.Manager import Manager
from System.UserSystem import UserSystem
from System.CourseSystem import CourseSystem

# Admin UI main class (inherits from Tk, encapsulates all interface logic)
class AdminUI(tk.Tk):
    def __init__(self, current_admin):
        super().__init__()
        self.title("GT-OOP Learning Management System - Admin Center")
        self.geometry("900x600")
        self.resizable(False, False)
        self.current_admin = current_admin  # Currently logged-in admin username

        # Initialize system instances
        self._init_systems()
        
        # Initialize interface: top title bar + function button area
        self._init_top_bar()
        self._init_function_buttons()
        
        # Configure interface style
        self._config_style()

    def _init_systems(self):
        """Initialize system core modules"""
        data_dir = os.path.join(project_root, "Data")
        # Initialize user system and course system
        self.user_system = UserSystem(os.path.join(data_dir, "UserAccount.json"))
        self.course_system = CourseSystem(os.path.join(data_dir, "Course.json"))

    def _init_top_bar(self):
        """Initialize top title and logout button"""
        top_frame = ttk.Frame(self, padding="15 10 15 10", style="TopBar.TFrame")
        top_frame.pack(fill=tk.X)

        # Title
        ttk.Label(
            top_frame,
            text=f"Admin Center - Current User: {self.current_admin}",
            font=("Arial", 14, "bold")
        ).pack(side=tk.LEFT)

        # Logout button
        ttk.Button(
            top_frame,
            text="Logout",
            command=self._logout,
            style="Quit.TButton"
        ).pack(side=tk.RIGHT)

    def _init_function_buttons(self):
        """Initialize three main function buttons (centered layout)"""
        func_frame = ttk.Frame(self, padding="50 100 100 100")
        func_frame.pack(fill=tk.BOTH, expand=True)

        # Button configuration
        func_buttons = [
            ("1. Batch Register User Accounts", self._open_batch_user_reg),
            ("2. Manage Courses", self._open_course_management),
            ("3. Manage All Accounts", self._open_all_account_management)
        ]

        # Generate buttons
        for text, cmd in func_buttons:
            ttk.Button(
                func_frame,
                text=text,
                command=cmd,
                width=30,
                padding="30 20",
                style="Func.TButton"
            ).pack(pady=25, fill=tk.X)

    def _logout(self):
        """Logout current admin account"""
        confirm = messagebox.askyesno("Confirm Logout", "Are you sure you want to logout?")
        if confirm:
            self.destroy()  # Close current admin window

    def _open_batch_user_reg(self):
        """Open batch user registration window"""
        # Create new child window
        self.batch_reg_window = tk.Toplevel(self)
        self.batch_reg_window.title("Batch Register User Accounts")
        self.batch_reg_window.geometry("800x550")
        self.batch_reg_window.resizable(False, False)

        # Create main container
        main_container = ttk.Frame(self.batch_reg_window, padding="20")
        main_container.pack(fill=tk.BOTH, expand=True)
        main_container.grid_rowconfigure(2, weight=1)
        main_container.grid_columnconfigure(0, weight=1)

        # 1. Title row
        ttk.Label(
            main_container,
            text="Batch Register User Accounts",
            font=("Arial", 12, "bold")
        ).grid(row=0, column=0, sticky="w", pady=(0, 20))

        ttk.Separator(main_container, orient="horizontal").grid(row=1, column=0, sticky="ew", pady=(0, 20))

        # 2. Manual input area
        input_frame = ttk.LabelFrame(main_container, text="Manual Input User Information", padding="20 15")
        input_frame.grid(row=2, column=0, sticky="nsew", pady=(0, 20))
        input_frame.grid_rowconfigure(1, weight=1)
        input_frame.grid_columnconfigure(0, weight=1)

        # Input instructions
        instructions_frame = ttk.Frame(input_frame)
        instructions_frame.grid(row=0, column=0, sticky="ew", pady=(0, 15))
        
        ttk.Label(
            instructions_frame,
            text="Please enter user information in the following format (one user per line):",
            font=("Arial", 10),
            foreground="#34495e"
        ).pack(anchor="w")
        
        example_text = "Student: 2024001,Zhang San,Zhang San,123456,Student\nTeacher: T001,Li Si,Li Si,123456,Teacher\nAdministrator: A001,Wang Wu,Wang Wu,123456,Administrator"
        example_label = ttk.Label(
            instructions_frame,
            text=example_text,
            font=("Courier New", 10),
            foreground="#2980b9",
            background="#ecf0f1",
            padding=10,
            wraplength=700
        ).pack(anchor="w", fill=tk.X, pady=(10, 5))
        
        ttk.Label(
            instructions_frame,
            text="Format: ID,ChineseName,EnglishName,Password,Role (Role is case-sensitive)",
            font=("Arial", 9, "italic"),
            foreground="#7f8c8d"
        ).pack(anchor="w", pady=(5, 0))

        # Text input area with scrollbar
        input_area_frame = ttk.Frame(input_frame)
        input_area_frame.grid(row=1, column=0, sticky="nsew")
        input_area_frame.grid_rowconfigure(0, weight=1)
        input_area_frame.grid_columnconfigure(0, weight=1)

        self.manual_text = tk.Text(
            input_area_frame,
            font=("Arial", 10),
            wrap=tk.WORD,
            height=10,
            relief="sunken",
            bd=1
        )
        self.manual_text.grid(row=0, column=0, sticky="nsew")

        scrollbar = ttk.Scrollbar(
            input_area_frame,
            orient="vertical",
            command=self.manual_text.yview
        )
        scrollbar.grid(row=0, column=1, sticky="ns")
        self.manual_text.configure(yscrollcommand=scrollbar.set)

        # 3. Bottom operation buttons
        btn_frame = ttk.Frame(main_container)
        btn_frame.grid(row=3, column=0, sticky="ew", pady=(10, 0))
        btn_frame.grid_columnconfigure(0, weight=1)  # Push buttons to the right

        ttk.Button(
            btn_frame,
            text="Confirm Batch Registration",
            command=self._confirm_batch_reg,
            style="Confirm.TButton",
            width=25
        ).pack(side=tk.RIGHT, padx=10)
        
        ttk.Button(
            btn_frame,
            text="Cancel",
            command=self.batch_reg_window.destroy,
            style="Cancel.TButton",
            width=15
        ).pack(side=tk.RIGHT)

    def _confirm_batch_reg(self):
        """Process batch registration from manual input"""
        if not self.manual_text.get("1.0", tk.END).strip():
            messagebox.showerror("Error", "Please enter user information first!")
            return

        # Process manual input data
        user_data_list = []
        lines = self.manual_text.get("1.0", tk.END).strip().split("\n")
        failed_ids = []

        for idx, line in enumerate(lines, 1):
            if line.strip():
                parts = line.strip().split(",")
                if len(parts) != 5:
                    failed_ids.append(f"Line {idx}: Format error, requires 5 fields (ID,ChineseName,EnglishName,Password,Role)")
                    continue

                # Parse fields
                user_id, chinese_name, english_name, password, role = [p.strip() for p in parts]

                # Validate required fields
                if not all([user_id, chinese_name, english_name, password, role]):
                    failed_ids.append(f"Line {idx}: Fields cannot be empty")
                    continue

                # Validate role
                valid_roles = ["Student", "Teacher", "Administrator"]
                if role not in valid_roles:
                    failed_ids.append(f"Line {idx}: Invalid role '{role}', must be one of {valid_roles}")
                    continue

                user_data_list.append({
                    "id": user_id,
                    "password": password,
                    "chinese_name": chinese_name,
                    "english_name": english_name,
                    "role": role,
                    "group": None  # Group only needed for students, processed later
                })

        # Batch create user objects and register
        for user_data in user_data_list:
            try:
                # Create different user types based on role
                role = user_data["role"]
                if role == "Student":
                    from User.Student import Student
                    user = Student(
                        ID=user_data["id"],
                        Password=user_data["password"],
                        ChineseName=user_data["chinese_name"],
                        EnglishName=user_data["english_name"],
                        Group=user_data["group"]
                    )
                elif role == "Teacher":
                    from User.Teacher import Teacher
                    user = Teacher(
                        ID=user_data["id"],
                        Password=user_data["password"],
                        ChineseName=user_data["chinese_name"],
                        EnglishName=user_data["english_name"],
                        Courses=[]
                    )
                elif role == "Administrator":
                    from User.Manager import Manager
                    user = Manager(
                        ID=user_data["id"],
                        Password=user_data["password"],
                        ChineseName=user_data["chinese_name"],
                        EnglishName=user_data["english_name"]
                    )

                # Register user
                success, msg = self.user_system.register_user(user)
                if not success:
                    failed_ids.append(f"{user_data['id']}: {msg}")
            except Exception as e:
                failed_ids.append(f"{user_data.get('id', f'Line {idx}')}: {str(e)}")

        success = len(failed_ids) == 0
        msg = f"Successfully registered {len(user_data_list)-len(failed_ids)} users, failed {len(failed_ids)} users"

        # Display registration results
        if success:
            messagebox.showinfo("Registration Successful", msg)
        else:
            error_msg = f"{msg}\nFailed list:\n" + "\n".join(failed_ids)
            messagebox.showerror("Registration Failed", error_msg)
            
        self.batch_reg_window.destroy()

    def _open_course_management(self):
        """Open course management window"""
        self.course_manage_window = tk.Toplevel(self)
        self.course_manage_window.title("Manage Courses")
        self.course_manage_window.geometry("900x600")
        self.course_manage_window.resizable(False, False)

        # Layout: top search area + middle course list + bottom operation buttons
        self._init_course_search()
        self._init_course_table()
        self._init_course_buttons()

        # Load course data
        self._load_course_data()

    def _init_course_search(self):
        search_frame = ttk.Frame(self.course_manage_window, padding="20 15 20 10")
        search_frame.pack(fill=tk.X)

        # Search criteria selection
        ttk.Label(search_frame, text="Search by:").pack(side=tk.LEFT, padx=5)
        self.search_type_var = tk.StringVar(value="id")
        
        ttk.Radiobutton(
            search_frame,
            text="Course ID",
            variable=self.search_type_var,
            value="id"
        ).pack(side=tk.LEFT, padx=10)
        
        ttk.Radiobutton(
            search_frame,
            text="Course Name",
            variable=self.search_type_var,
            value="name"
        ).pack(side=tk.LEFT, padx=10)

        # Search input box
        self.search_key_var = tk.StringVar()
        search_entry = ttk.Entry(
            search_frame,
            textvariable=self.search_key_var,
            width=30,
            font=("Arial", 10)
        )
        search_entry.pack(side=tk.LEFT, padx=15)

        # Search/reset buttons
        ttk.Button(
            search_frame,
            text="Search",
            command=self._search_course
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            search_frame,
            text="Reset",
            command=self._reset_course_search
        ).pack(side=tk.LEFT, padx=5)

    def _init_course_table(self):
        """Initialize course table with columns: ID, Name, Teacher, Time, Classroom, Status"""
        table_frame = ttk.Frame(self.course_manage_window, padding="20 10 20 10")
        table_frame.pack(fill=tk.BOTH, expand=True)

        # Scrollbars
        scrollbar_y = ttk.Scrollbar(table_frame, orient=tk.VERTICAL)
        scrollbar_x = ttk.Scrollbar(table_frame, orient=tk.HORIZONTAL)

        # Table configuration
        self.course_table = ttk.Treeview(
            table_frame,
            columns=("course_id", "course_name", "teacher", "time", "classroom", "status"),
            show="headings",
            yscrollcommand=scrollbar_y.set,
            xscrollcommand=scrollbar_x.set
        )

        # Configure column headings and widths
        self.course_table.heading("course_id", text="Course ID", anchor=tk.CENTER)
        self.course_table.heading("course_name", text="Course Name", anchor=tk.CENTER)
        self.course_table.heading("teacher", text="Teacher", anchor=tk.CENTER)
        self.course_table.heading("time", text="Course Time", anchor=tk.CENTER)
        self.course_table.heading("classroom", text="Classroom", anchor=tk.CENTER)
        self.course_table.heading("status", text="Status", anchor=tk.CENTER)

        self.course_table.column("course_id", width=100, anchor=tk.CENTER)
        self.course_table.column("course_name", width=150, anchor=tk.CENTER)
        self.course_table.column("teacher", width=120, anchor=tk.CENTER)
        self.course_table.column("time", width=150, anchor=tk.CENTER)
        self.course_table.column("classroom", width=120, anchor=tk.CENTER)
        self.course_table.column("status", width=100, anchor=tk.CENTER)

        # Bind scrollbars
        scrollbar_y.config(command=self.course_table.yview)
        scrollbar_x.config(command=self.course_table.xview)

        # Layout table and scrollbars
        scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
        scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
        self.course_table.pack(fill=tk.BOTH, expand=True)

    def _init_course_buttons(self):
        btn_frame = ttk.Frame(self.course_manage_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X)

        ttk.Button(
            btn_frame,
            text="Create Course",
            command=self._create_course,
            style="Create.TButton"
        ).pack(side=tk.LEFT, padx=10)
        
        ttk.Button(
            btn_frame,
            text="Edit Course",
            command=self._edit_course
        ).pack(side=tk.LEFT, padx=10)
        
        ttk.Button(
            btn_frame,
            text="Delete Course",
            command=self._delete_course,
            style="Delete.TButton"
        ).pack(side=tk.LEFT, padx=10)

    def _load_course_data(self):
        """Load and display all courses"""
        # Clear existing data
        for item in self.course_table.get_children():
            self.course_table.delete(item)

        # Get all courses from CourseSystem
        courses = self.course_system.get_all_courses()

        # Insert data into table
        for course in courses:
            # Get teacher name
            teacher = self.user_system.get_user_by_id(course.Teacher.ID)
            teacher_name = teacher.EnglishName if teacher else "Unknown Teacher"
            
            # Course status
            status = "Active" if len(course.Students) > 0 else "Inactive"
            
            # Insert course data
            self.course_table.insert("", tk.END, values=(
                course.ID,
                course.CourseName,
                teacher_name,
                course.CourseTime,
                course.Classroom,
                status
            ))

    def _search_course(self):
        search_type = self.search_type_var.get()
        search_key = self.search_key_var.get().strip()
        
        if not search_key:
            messagebox.showwarning("提示", "Please enter search keyword!")
            return

        # Get all courses
        courses = self.course_system.get_all_courses()
        filtered_courses = []
        
        for course in courses:
            if search_type == "id" and search_key in course.ID:
                filtered_courses.append(course)
            elif search_type == "name" and search_key in course.CourseName:
                filtered_courses.append(course)

        # Clear existing data
        for item in self.course_table.get_children():
            self.course_table.delete(item)

        # Insert filtered data
        for course in filtered_courses:
            teacher = self.user_system.get_user_by_id(course.Teacher.ID)
            teacher_name = teacher.EnglishName if teacher else "Unknown Teacher"
            status = "Active" if len(course.Students) > 0 else "Inactive"
            
            self.course_table.insert("", tk.END, values=(
                course.ID,
                course.CourseName,
                teacher_name,
                course.CourseTime,
                course.Classroom,
                status
            ))

    def _reset_course_search(self):
        self.search_key_var.set("")
        self._load_course_data()  # Reload all courses

    def _create_course(self):
        """Create new course window"""
        create_window = tk.Toplevel(self.course_manage_window)
        create_window.title("Create Course")
        create_window.geometry("500x350")
        create_window.resizable(False, False)

        form_frame = ttk.Frame(create_window, padding="30 20 30 20")
        form_frame.pack(fill=tk.BOTH, expand=True)

        # Course ID
        ttk.Label(form_frame, text="Course ID:").grid(row=0, column=0, sticky=tk.W, pady=10)
        self.create_course_id = ttk.Entry(form_frame, width=30)
        self.create_course_id.grid(row=0, column=1, pady=10)

        # Course Name
        ttk.Label(form_frame, text="Course Name:").grid(row=1, column=0, sticky=tk.W, pady=10)
        self.create_course_name = ttk.Entry(form_frame, width=30)
        self.create_course_name.grid(row=1, column=1, pady=10)

        # Teacher ID
        ttk.Label(form_frame, text="Teacher ID:").grid(row=2, column=0, sticky=tk.W, pady=10)
        self.create_course_teacher = ttk.Entry(form_frame, width=30)
        self.create_course_teacher.grid(row=2, column=1, pady=10)

        # Course Time
        ttk.Label(form_frame, text="Course Time:").grid(row=3, column=0, sticky=tk.W, pady=10)
        self.create_course_time = ttk.Entry(form_frame, width=30)
        self.create_course_time.grid(row=3, column=1, pady=10)

        # Classroom
        ttk.Label(form_frame, text="Classroom:").grid(row=4, column=0, sticky=tk.W, pady=10)
        self.create_course_classroom = ttk.Entry(form_frame, width=30)
        self.create_course_classroom.grid(row=4, column=1, pady=10)

        # Confirm/Cancel buttons
        btn_frame = ttk.Frame(create_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X)
        ttk.Button(btn_frame, text="Confirm Create", command=lambda: self._confirm_create_course(create_window)).pack(side=tk.RIGHT, padx=10)
        ttk.Button(btn_frame, text="Cancel", command=create_window.destroy).pack(side=tk.RIGHT)

    def _confirm_create_course(self, window):
        # Get form data
        course_id = self.create_course_id.get().strip()
        course_name = self.create_course_name.get().strip()
        teacher_id = self.create_course_teacher.get().strip()
        course_time = self.create_course_time.get().strip()
        classroom = self.create_course_classroom.get().strip()

        # Basic form validation
        if not (course_id and course_name and teacher_id and course_time and classroom):
            messagebox.showerror("Error", "Please fill in all required fields!")
            return

        # Verify teacher exists
        teacher = self.user_system.get_user_by_id(teacher_id, role_filter=["Teacher"])
        if not teacher:
            messagebox.showerror("Error", f"Teacher ID {teacher_id} does not exist or is not a teacher")
            return

        # Create course using CourseSystem
        try:
            course = self.course_system.CreateCourse(
                ID=course_id,
                Teacher=teacher,
                CourseName=course_name,
                CourseTime=course_time,
                Classroom=classroom,
                Students=[],
                Assignments=[]
            )
            messagebox.showinfo("Creation Successful", f"Course {course_name}(ID:{course_id}) created successfully!")
            window.destroy()
            self._load_course_data()  # Reload course list
        except Exception as e:
            messagebox.showerror("Creation Failed", f"Error creating course: {str(e)}")

    def _edit_course(self):
        """Edit selected course"""
        selected_items = self.course_table.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select a course to modify first!")
            return

        selected_item = selected_items[0]
        selected_course_data = self.course_table.item(selected_item, "values")
        course_id = selected_course_data[0]

        # Get course object
        course = self.course_system.get_course_by_id(course_id)
        if not course:
            messagebox.showerror("Error", f"Course ID {course_id} does not exist")
            return

        # Create edit window
        edit_window = tk.Toplevel(self.course_manage_window)
        edit_window.title("Edit Course")
        edit_window.geometry("500x350")
        edit_window.resizable(False, False)

        form_frame = ttk.Frame(edit_window, padding="30 20 30 20")
        form_frame.pack(fill=tk.BOTH, expand=True)

        # Course ID (non-editable)
        ttk.Label(form_frame, text="Course ID:").grid(row=0, column=0, sticky=tk.W, pady=10)
        ttk.Label(form_frame, text=course.ID).grid(row=0, column=1, sticky=tk.W, pady=10)

        # Course Name
        ttk.Label(form_frame, text="Course Name:").grid(row=1, column=0, sticky=tk.W, pady=10)
        self.edit_course_name = ttk.Entry(form_frame, width=30)
        self.edit_course_name.insert(0, course.CourseName)
        self.edit_course_name.grid(row=1, column=1, pady=10)

        # Teacher ID
        ttk.Label(form_frame, text="Teacher ID:").grid(row=2, column=0, sticky=tk.W, pady=10)
        self.edit_course_teacher = ttk.Entry(form_frame, width=30)
        self.edit_course_teacher.insert(0, course.Teacher.ID)
        self.edit_course_teacher.config(state='disabled', foreground='black')
        self.edit_course_teacher.grid(row=2, column=1, pady=10)

        # Course Time
        ttk.Label(form_frame, text="Course Time:").grid(row=3, column=0, sticky=tk.W, pady=10)
        self.edit_course_time = ttk.Entry(form_frame, width=30)
        self.edit_course_time.insert(0, course.CourseTime)
        self.edit_course_time.grid(row=3, column=1, pady=10)

        # Classroom
        ttk.Label(form_frame, text="Classroom:").grid(row=4, column=0, sticky=tk.W, pady=10)
        self.edit_course_classroom = ttk.Entry(form_frame, width=30)
        self.edit_course_classroom.insert(0, course.Classroom)
        self.edit_course_classroom.grid(row=4, column=1, pady=10)

        # Confirm/Cancel buttons
        btn_frame = ttk.Frame(edit_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X)
        ttk.Button(btn_frame, text="Confirm Modify", command=lambda: self._confirm_edit_course(edit_window, course)).pack(side=tk.RIGHT, padx=10)
        ttk.Button(btn_frame, text="Cancel", command=edit_window.destroy).pack(side=tk.RIGHT)

    def _confirm_edit_course(self, window, course):
        # Get form data
        course_name = self.edit_course_name.get().strip()
        teacher_id = self.edit_course_teacher.get().strip()
        course_time = self.edit_course_time.get().strip()
        classroom = self.edit_course_classroom.get().strip()

        # Basic validation
        if not (course_name and teacher_id and course_time and classroom):
            messagebox.showerror("Error", "Please fill in all required fields!")
            return

        # Verify teacher exists
        teacher = self.user_system.get_user_by_id(teacher_id, role_filter=["Teacher"])
        if not teacher:
            messagebox.showerror("Error", f"Teacher ID {teacher_id} does not exist or is not a teacher")
            return

        # Update course information
        try:
            # Update course using course system
            updated_course = self.course_system.UpdateCourse(
                course_id=course.ID,
                CourseName=course_name,
                Teacher=teacher,
                CourseTime=course_time,
                Classroom=classroom
            )
            messagebox.showinfo("Modification Successful", f"Course {course_name}(ID:{course.ID}) modified successfully!")
            window.destroy()
            self._load_course_data()  # Reload course list
        except Exception as e:
            messagebox.showerror("Modification Failed", f"Error modifying course: {str(e)}")

    def _delete_course(self):
        # Get selected course
        selected_items = self.course_table.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select a course to delete first!")
            return

        selected_item = selected_items[0]
        selected_course_data = self.course_table.item(selected_item, "values")
        course_id = selected_course_data[0]
        course_name = selected_course_data[1]

        # Confirm deletion
        confirm = messagebox.askyesno(
            "Confirm Deletion",
            f"Are you sure you want to delete course {course_name}(ID:{course_id})? Deletion cannot be undone!"
        )
        if confirm:
            # Delete course using CourseSystem
            try:
                success = self.course_system.DeleteCourse(course_id)
                if success:
                    messagebox.showinfo("Deletion Successful", f"Course {course_name}(ID:{course_id}) has been deleted!")
                    self._load_course_data()  # Reload course list
                else:
                    messagebox.showerror("Deletion Failed", f"Course {course_id} does not exist or cannot be deleted")
            except Exception as e:
                messagebox.showerror("Deletion Failed", f"Error deleting course: {str(e)}")

    def _open_all_account_management(self):
        self.account_manage_window = tk.Toplevel(self)
        self.account_manage_window.title("Manage All Accounts")
        self.account_manage_window.geometry("900x600")
        self.account_manage_window.resizable(False, False)

        # Layout: top filter+search area + middle account list + bottom operation buttons
        self._init_account_filter()
        self._init_account_table()
        self._init_account_buttons()

        # Load account data
        self._load_account_data()

    def _init_account_filter(self):
        filter_frame = ttk.Frame(self.account_manage_window, padding="20 15 20 10")
        filter_frame.pack(fill=tk.X)

        # User type filter
        ttk.Label(filter_frame, text="User Type:").pack(side=tk.LEFT, padx=5)
        self.account_type_var = tk.StringVar(value="all")
        type_frame = ttk.Frame(filter_frame)
        type_frame.pack(side=tk.LEFT, padx=5)
        
        ttk.Radiobutton(type_frame, text="All", variable=self.account_type_var, value="all").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(type_frame, text="Student", variable=self.account_type_var, value="student").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(type_frame, text="Teacher", variable=self.account_type_var, value="teacher").pack(side=tk.LEFT, padx=5)
        ttk.Radiobutton(type_frame, text="Administrator", variable=self.account_type_var, value="admin").pack(side=tk.LEFT, padx=5)

        # Filter button
        ttk.Button(filter_frame, text="Filter", command=self._filter_account).pack(side=tk.LEFT, padx=10)

        # Keyword search
        ttk.Label(filter_frame, text="Search:").pack(side=tk.LEFT, padx=15)
        self.account_search_var = tk.StringVar()
        search_entry = ttk.Entry(filter_frame, textvariable=self.account_search_var, width=30)
        search_entry.pack(side=tk.LEFT, padx=5)
        ttk.Button(filter_frame, text="Search", command=self._search_account).pack(side=tk.LEFT, padx=5)

    def _init_account_table(self):
        table_frame = ttk.Frame(self.account_manage_window, padding="20 10 20 10")
        table_frame.pack(fill=tk.BOTH, expand=True)

        # Scrollbars
        scrollbar_y = ttk.Scrollbar(table_frame, orient=tk.VERTICAL)
        scrollbar_x = ttk.Scrollbar(table_frame, orient=tk.HORIZONTAL)

        # Table column configuration
        self.account_table = ttk.Treeview(
            table_frame,
            columns=("user_id", "username", "user_type", "status"),
            show="headings",
            yscrollcommand=scrollbar_y.set,
            xscrollcommand=scrollbar_x.set
        )

        # Column headings and widths
        self.account_table.heading("user_id", text="Account ID", anchor=tk.CENTER)
        self.account_table.heading("username", text="Username", anchor=tk.CENTER)
        self.account_table.heading("user_type", text="User Type", anchor=tk.CENTER)
        self.account_table.heading("status", text="Status", anchor=tk.CENTER)

        self.account_table.column("user_id", width=150, anchor=tk.CENTER)
        self.account_table.column("username", width=200, anchor=tk.CENTER)
        self.account_table.column("user_type", width=150, anchor=tk.CENTER)
        self.account_table.column("status", width=150, anchor=tk.CENTER)

        # Bind scrollbars
        scrollbar_y.config(command=self.account_table.yview)
        scrollbar_x.config(command=self.account_table.xview)

        scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
        scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
        self.account_table.pack(fill=tk.BOTH, expand=True)

    def _init_account_buttons(self):
        btn_frame = ttk.Frame(self.account_manage_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X)

        ttk.Button(
            btn_frame,
            text="Modify Account Information",
            command=self._edit_account,
            style="Edit.TButton"
        ).pack(side=tk.LEFT, padx=10)
        
        ttk.Button(
            btn_frame,
            text="Delete Account",
            command=self._delete_account,
            style="Delete.TButton"
        ).pack(side=tk.LEFT, padx=10)

    def _load_account_data(self):
        # Clear existing data
        for item in self.account_table.get_children():
            self.account_table.delete(item)

        # Get user type filter
        user_type = self.account_type_var.get()
        role_filter = None
        if user_type == "student":
            role_filter = ["Student"]
        elif user_type == "teacher":
            role_filter = ["Teacher"]
        elif user_type == "admin":
            role_filter = ["Admin"]

        # Load user data
        try:
            with open(self.user_system.user_data_path, "r", encoding="utf-8") as f:
                users = json.load(f)
                
            # Filter and display user data
            for user in users:
                # Apply role filter
                if role_filter and user["role"] not in role_filter:
                    continue
                    
                # Account status (simplified)
                status = "Normal"
                self.account_table.insert("", tk.END, values=(
                    user["id"],
                    user["english_name"],
                    user["role"],
                    status
                ))
        except Exception as e:
            messagebox.showerror("Error", f"Failed to load account data: {str(e)}")

    def _filter_account(self):
        self._load_account_data()  # Reload data with current filter

    def _search_account(self):
        search_key = self.account_search_var.get().strip()
        if not search_key:
            messagebox.showwarning("Error", "Please enter search keyword!")
            return

        # Load all user data
        try:
            with open(self.user_system.user_data_path, "r", encoding="utf-8") as f:
                existing_users = json.load(f)
                
            # Filter data
            filtered_users = []
            for user in existing_users:
                # Apply role filter
                user_type = self.account_type_var.get()
                if (user_type != "all" and user["role"] != user_type.capitalize()):
                    continue
                    
                # Keyword match
                if (search_key in user["id"] or 
                    search_key in user.get("chinese_name", "") or 
                    search_key in user.get("english_name", "")):
                    filtered_users.append(user)

            # Clear existing data
            for item in self.account_table.get_children():
                self.account_table.delete(item)
                
            # Insert filtered data
            for user in filtered_users:
                status = "Normal"
                self.account_table.insert("", tk.END, values=(
                    user["id"],
                    user["english_name"],
                    user["role"],
                    status
                ))
        except Exception as e:
            messagebox.showerror("Error", f"Failed to search accounts: {str(e)}")

    def _edit_account(self):
        # Get selected account
        selected_items = self.account_table.selection()
        if not selected_items:
            messagebox.showwarning("Error", "Please select an account to modify first!")
            return

        selected_item = selected_items[0]
        selected_account = self.account_table.item(selected_item, "values")
        user_id = selected_account[0]
        username = selected_account[1]
        user_type = selected_account[2]

        # Get user object
        user = self.user_system.get_user_by_id(user_id)
        if not user:
            messagebox.showerror("Error", f"Account {user_id} does not exist")
            return

        # Create edit window
        edit_window = tk.Toplevel(self.account_manage_window)
        edit_window.title(f"Modify Account - {username}")
        edit_window.geometry("500x400")
        edit_window.resizable(False, False)

        # Form layout
        form_frame = ttk.Frame(edit_window, padding="30 20 30 20")
        form_frame.pack(fill=tk.BOTH, expand=True)

        # Account ID (non-editable)
        ttk.Label(form_frame, text="Account ID:").grid(row=0, column=0, sticky=tk.W, pady=15)
        ttk.Label(form_frame, text=user_id).grid(row=0, column=1, sticky=tk.W, pady=15)
        self.edit_user_id = user_id

        # Username (editable)
        ttk.Label(form_frame, text="Username:").grid(row=1, column=0, sticky=tk.W, pady=15)
        self.edit_username = ttk.Entry(form_frame, width=30)
        self.edit_username.insert(0, username)
        self.edit_username.grid(row=1, column=1, pady=15)

        # User type (non-editable, display only)
        ttk.Label(form_frame, text="User Type:").grid(row=2, column=0, sticky=tk.W, pady=15)
        ttk.Label(form_frame, text=user_type).grid(row=2, column=1, sticky=tk.W, pady=15)

        # Account status (editable)
        ttk.Label(form_frame, text="Account Status:").grid(row=3, column=0, sticky=tk.W, pady=15)
        self.edit_status_var = tk.StringVar(value=selected_account[3])
        status_frame = ttk.Frame(form_frame)
        status_frame.grid(row=3, column=1, sticky=tk.W)
        
        ttk.Radiobutton(status_frame, text="Normal", variable=self.edit_status_var, value="Normal").pack(side=tk.LEFT, padx=10)
        ttk.Radiobutton(status_frame, text="Disabled", variable=self.edit_status_var, value="Disabled").pack(side=tk.LEFT, padx=10)

        # Reset password (optional)
        ttk.Label(form_frame, text="Reset Password:").grid(row=4, column=0, sticky=tk.W, pady=15)
        self.reset_password_var = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            form_frame,
            text="Reset to initial password (123456)",
            variable=self.reset_password_var
        ).grid(row=4, column=1, sticky=tk.W, pady=15)

        # Confirm/Cancel buttons
        btn_frame = ttk.Frame(edit_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X)
        ttk.Button(btn_frame, text="Confirm Modify", command=lambda: self._confirm_edit_account(edit_window, user)).pack(side=tk.RIGHT, padx=10)
        ttk.Button(btn_frame, text="Cancel", command=edit_window.destroy).pack(side=tk.RIGHT)

    def _confirm_edit_account(self, window, user):
        # Get modified data
        new_username = self.edit_username.get().strip()
        new_status = self.edit_status_var.get()
        need_reset_pwd = self.reset_password_var.get()

        # Basic validation
        if not new_username:
            messagebox.showerror("Error", "Username cannot be empty!")
            return

        # Update user information
        try:
            # Update user using UserSystem update method
            success, msg = self.user_system.update_user(
                user_id=user.ID,
                new_chinese_name=new_username,
                reset_password=need_reset_pwd
            )
            
            if success:
                reset_msg = " (Password has been reset)" if need_reset_pwd else ""
                messagebox.showinfo("Modification Successful", f"Account {self.edit_user_id} ({new_username}) modified successfully!{reset_msg}")
                window.destroy()
                self._load_account_data()  # Reload account list
            else:
                messagebox.showerror("Modification Failed", f"Error modifying account: {msg}")
        except Exception as e:
            messagebox.showerror("Modification Failed", f"Error modifying account: {str(e)}")

    def _delete_account(self):
        """Delete selected account"""
        selected_items = self.account_table.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select an account to delete first!")
            return

        selected_item = selected_items[0]
        selected_account = self.account_table.item(selected_item, "values")
        user_id = selected_account[0]
        username = selected_account[1]

        # Prevent deleting current admin account
        if user_id == self.current_admin:
            messagebox.showerror("Error", "Cannot delete currently logged-in admin account!")
            return

        # Confirm deletion
        confirm = messagebox.askyesno(
            "Confirm Deletion",
            f"Are you sure you want to delete account {username} (ID: {user_id})? Deletion cannot be undone!"
        )
        if not confirm:
            return

        # Delete account using UserSystem
        try:
            success, msg = self.user_system.delete_user(user_id)
            if success:
                messagebox.showinfo("Deletion Successful", f"Account {user_id} ({username}) has been deleted successfully!")
                self._load_account_data()  # Reload account list
            else:
                messagebox.showerror("Deletion Failed", f"Error deleting account: {msg}")
        except Exception as e:
            messagebox.showerror("Deletion Failed", f"Error deleting account: {str(e)}")

    def _config_style(self):
        style = ttk.Style()
        
        # Top title bar style
        style.configure("TopBar.TFrame", background="#f0f0f0")
        
        # Function button style
        style.configure("Func.TButton", font=("Arial", 11), padding=10)
        style.map("Func.TButton", background=[("active", "#e0e0e0")])
        
        # Confirm button style (green)
        style.configure("Confirm.TButton", font=("Arial", 10, "bold"), foreground="black", background="#28a745")
        style.map("Confirm.TButton", background=[("active", "#218838")])
        
        # Cancel button style
        style.configure("Cancel.TButton", font=("Arial", 10), foreground="black", background="#6c757d")
        style.map("Cancel.TButton", background=[("active", "#5a6268")])
        
        # Create button style (green)
        style.configure("Create.TButton", font=("Arial", 10, "bold"), foreground="black", background="#28a745")
        style.map("Create.TButton", background=[("active", "#218838")])
        
        # Edit button style (blue)
        style.configure("Edit.TButton", font=("Arial", 10, "bold"), foreground="black", background="#007bff")
        style.map("Edit.TButton", background=[("active", "#0069d9")])
        
        # Delete button style (red)
        style.configure("Delete.TButton", font=("Arial", 10, "bold"), foreground="black", background="#dc3545")
        style.map("Delete.TButton", background=[("active", "#c82333")])
        
        # Quit button style
        style.configure("Quit.TButton", font=("Arial", 10), foreground="black", background="#6c757d")
        style.map("Quit.TButton", background=[("active", "#5a6268")])

    def run(self):
        """Run the admin UI interface"""
        self.mainloop()

# Run entry point
if __name__ == "__main__":
    # In actual project, current_admin should be passed from login interface
    admin_ui = AdminUI(current_admin="admin001")  # Admin ID
    admin_ui.run()